/**
 * 
 */
package com.sevenpay.wx.jybcj.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sevenpay.wx.connection.HttpClient;
import com.sevenpay.wx.connection.WxUrlConstants;
import com.sevenpay.wx.connection.bean.AccessToken4WebResponseBean;
import com.sevenpay.wx.connection.bean.UserInfo4Web;
import com.sevenpay.wx.jybcj.SysConfig;
import com.sevenpay.wx.jybcj.bean.JybcjBean;
import com.sevenpay.wx.jybcj.bean.YbCjInfo;
import com.sevenpay.wx.jybcj.bean.YbCjInfoExample;
import com.sevenpay.wx.jybcj.bean.YbDetailInfo;
import com.sevenpay.wx.jybcj.bean.YbDetailInfoExample;
import com.sevenpay.wx.jybcj.bean.YbInfo;
import com.sevenpay.wx.jybcj.bean.YbUserInfo;
import com.sevenpay.wx.jybcj.commons.YbCode;
import com.sevenpay.wx.jybcj.dao.YbCjInfoMapper;
import com.sevenpay.wx.jybcj.dao.YbDetailInfoMapper;
import com.sevenpay.wx.jybcj.dao.YbInfoMapper;
import com.sevenpay.wx.jybcj.dao.YbUserInfoMapper;

/**
 * @author kunwang.li
 *
 */
@Service
public class JybcjService {

	private static Logger logger = LoggerFactory.getLogger(JybcjService.class);

	@Autowired
	private HttpClient httpClient;

	@Autowired
	private SysConfig sysConfig;

	@Autowired
	private JybcjServiceSupport jybcjServiceSupport;
	@Autowired
	private YbUserInfoMapper ybUserInfoMapper;
	@Autowired
	private YbCjInfoMapper ybCjInfoMapper;
	@Autowired
	private YbDetailInfoMapper ybDetailInfoMapper;
	@Autowired
	private YbInfoMapper ybInfoMapper;

	public JybcjBean entry(String code, String state) throws Exception {
		try {
			String resMsg = null;
			resMsg = httpClient.send(
					WxUrlConstants.getUrl("accessToken4Web", sysConfig.getAppId(), sysConfig.getAppSecret(), code), "",
					WxUrlConstants.charset);

			AccessToken4WebResponseBean atrb = JSONObject.parseObject(resMsg, AccessToken4WebResponseBean.class);
			if (null == atrb || StringUtils.isNotBlank(atrb.getErrCode())) {
				throw new RuntimeException("获取accessToken4Web失败: [" + atrb.getErrCode() + "]" + atrb.getErrMsg());
			}

			YbUserInfo ybUserInfo = ybUserInfoMapper.selectByPrimaryKey(atrb.getOpenId());

			if (null == ybUserInfo) {
				resMsg = httpClient.send(WxUrlConstants.getUrl("userInfo4Web", atrb.getAccessToken(), atrb.getOpenId()),
						"", WxUrlConstants.charset);

				UserInfo4Web userInfo4Web = JSONObject.parseObject(resMsg, UserInfo4Web.class);

				if (null == userInfo4Web || StringUtils.isNotBlank(userInfo4Web.getErrCode())) {
					throw new RuntimeException(
							"获取userInfo4Web失败: [" + userInfo4Web.getErrCode() + "]" + userInfo4Web.getErrMsg());
				}

				ybUserInfo = new YbUserInfo();
				BeanUtils.copyProperties(userInfo4Web, ybUserInfo);
				// try {
				ybUserInfoMapper.insert(ybUserInfo);
				// } catch(DuplicateMemberException e1) {
				//
				// }
			}

			return entry(atrb.getOpenId());

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	public JybcjBean entry(String openId) {

		JybcjBean jybcjBean = new JybcjBean();

		YbUserInfo ybUserInfo = ybUserInfoMapper.selectByPrimaryKey(openId);

		YbInfo ybInfo = ybInfoMapper.selectByPrimaryKey(ybUserInfo.getOpenId());

		YbDetailInfoExample ybDetailInfoExample = new YbDetailInfoExample();
		ybDetailInfoExample.createCriteria().andOpenIdEqualTo(ybUserInfo.getOpenId());
		List<YbDetailInfo> ybDetailInfoList = ybDetailInfoMapper.selectByExample(ybDetailInfoExample);

		YbCjInfoExample ybCjInfoExample = new YbCjInfoExample();
		ybCjInfoExample.createCriteria().andOpenIdEqualTo(ybUserInfo.getOpenId());
		List<YbCjInfo> ybCjInfoList = ybCjInfoMapper.selectByExample(ybCjInfoExample);

		jybcjBean.setYbInfo(ybInfo);
		jybcjBean.setYbDetailInfoList(ybDetailInfoList);
		jybcjBean.setYbCjInfoList(ybCjInfoList);
		jybcjBean.setYbUserInfo(ybUserInfo);

		return jybcjBean;
	}

	/**
	 * 开启集月饼活动
	 * 
	 * @param openId
	 * @return
	 */
	public JybcjBean start(String openId) {
		SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String tranDatetime = datetimeFormat.format(new Date());

		YbInfo ybInfo = new YbInfo();
		ybInfo.setOpenId(openId);
		ybInfo.setTranDate(tranDatetime.substring(0, 8));
		ybInfo.setTranTime(tranDatetime.substring(8));
		ybInfo.setYbFull("0");
		ybInfoMapper.insertSelective(ybInfo);

		return entry(openId);
	}

	/**
	 * 选择自己的月饼
	 * 
	 * @param openId
	 * @param ybCode
	 * @return
	 */
	public boolean selectYb(String openId, YbCode ybCode) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		YbInfo ybInfo = new YbInfo();
		{
			ybInfo.setOpenId(openId);
			ybInfo.setSelectYbCode(ybCode.toString());
		}

		YbDetailInfo detailInfo = new YbDetailInfo();
		{
			detailInfo.setOpenId(openId);
			detailInfo.setYbCode(ybCode.toString());
			detailInfo.setYbStatus("1");
			detailInfo.setSenderOpenId(openId);
			detailInfo.setSendDatetime(sdf.format(new Date()));
		}

		List<YbDetailInfo> list = new ArrayList<YbDetailInfo>(5);

		list.add(detailInfo);

		for (YbCode _ybCode : YbCode.values()) {
			if (_ybCode != ybCode) {
				YbDetailInfo ybd = new YbDetailInfo();
				{
					ybd.setOpenId(openId);
					ybd.setYbCode(ybCode.toString());
					ybd.setYbStatus("0");
					ybd.setSenderOpenId("");
					ybd.setSendDatetime("");
				}
				list.add(ybd);
			}
		}

		jybcjServiceSupport.selectYb(ybInfo, list);
		return true;
	}

	public String sendEntry(String code, String state) throws Exception {

		try {
			String resMsg = null;
			resMsg = httpClient.send(
					WxUrlConstants.getUrl("accessToken4Web", sysConfig.getAppId(), sysConfig.getAppSecret(), code), "",
					WxUrlConstants.charset);

			AccessToken4WebResponseBean atrb = JSONObject.parseObject(resMsg, AccessToken4WebResponseBean.class);
			if (null == atrb || StringUtils.isNotBlank(atrb.getErrCode())) {
				throw new RuntimeException("获取accessToken4Web失败: [" + atrb.getErrCode() + "]" + atrb.getErrMsg());
			}

			return atrb.getOpenId();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}

	}

	/**
	 * 赠送好友月饼
	 * 
	 * @param openId
	 * @param senderOpenId
	 * @param ybCode
	 * @return
	 */
	public boolean sendYb(String openId, String senderOpenId, YbCode ybCode) {

		YbDetailInfo record = new YbDetailInfo();
		record.setSendDatetime(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		record.setSenderOpenId(senderOpenId);
		record.setYbCode(ybCode.toString());
		record.setYbStatus("1");
		YbDetailInfoExample example = new YbDetailInfoExample();
		example.createCriteria().andOpenIdEqualTo(openId).andYbStatusEqualTo("0");

		int count = ybDetailInfoMapper.updateByExampleSelective(record, example);
		if (count > 0) {
			return true;
		} else {
			return false;
		}

	}

}
